package cn.edu.hstc.wm.ui.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import cn.edu.hstc.wm.AppApplication;
import cn.edu.hstc.wm.AppConfigs;
import cn.edu.hstc.wm.R;
import cn.edu.hstc.wm.adapter.StoreFragmentAdapter;
import cn.edu.hstc.wm.bean.Store;
import cn.edu.hstc.wm.service.AppConfigService;
import cn.edu.hstc.wm.service.StoreService;
import cn.edu.hstc.wm.ui.StoreItemActivity;
import cn.edu.hstc.wm.ui.base.BaseFragment;
import cn.edu.hstc.wm.utils.IntentUtil;
import cn.edu.hstc.wm.utils.LogUtil;
import cn.edu.hstc.wm.widget.CustomToast;
import cn.edu.hstc.wm.widget.XListView;
import cn.edu.hstc.wm.widget.XListView.IXListViewListener;

/**
 * @ClassName: StoreFragment
 * @Description: 显示商铺模式的Fragment
 * 
 * @ModificationHistory
 */
public class StoreMode extends BaseFragment implements IXListViewListener, OnItemClickListener, LoadFailedFragment.CallBack {
	/** */
	public static final String TAG = StoreMode.class.getSimpleName();
	public static final String INTENT_URL = "STORE_FRAGMENT_STORE";

	/** Fragment 需要设置的显示方法类型 */
	private final int FRAGMENT_TYPE_REMOVE = 0x00;
	private final int FRAGMENT_TYPE_ADD = 0x01;
	private final int FRAGMENT_TYPE_REPLACE = 0x02;

	/** 当前最后一个数据所在的位置 */
	private int mCurDataIndex = 0;
	/** 最大的位置 */
	private int mMaxIndex = 0;

	/** 获取到的店铺实体类 集合 */
	private List<Store> mStoreList;
	private View mRootView;
	private XListView xListView;
	private StoreFragmentAdapter mAdapter;

	/** 正在加载界面 */
	private LoadingFragment mLoadingFragment;
	/** 加载失败界面 */
	private LoadFailedFragment mLoadFailedFragment;

	private Handler mHandler;

	/**
	 * 获得该实例的方法
	 * 
	 * @param bundle
	 *            携带的数据
	 * @return
	 */
	public static StoreMode getInstance(Bundle bundle) {
		StoreMode storeMode = new StoreMode();
		storeMode.setArguments(bundle);
		return storeMode;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mRootView = inflater.inflate(R.layout.store_fragment_layout, null);
		mHandler = new Handler();
		// 开始显示正在加载
		showLoadingView(true);

		// 先获取所有的个数
		new GetStoreCountTask().execute(0);

		initListView();
		// 获取数据
		// initData();
		return mRootView;
	}

	/**
	 * 设置是否显示正在加载界面
	 * 
	 * @param flag
	 *            true 显示正在加载 ;false 不显示正在加载
	 */
	private void showLoadingView(boolean flag) {
		if (flag) {
			// 正在加载页面显示
			mLoadingFragment = LoadingFragment.getInstance(getArguments());
			manageFragment(FRAGMENT_TYPE_REPLACE, mLoadingFragment);
		} else {
			// 移除正在加载显示页面
			if (mLoadingFragment != null) {
				manageFragment(FRAGMENT_TYPE_REMOVE, mLoadingFragment);
			}
		}
	}

	/**
	 * 设置是否显示加载失败界面
	 * 
	 * @param flag
	 *            true 显示失败界面;false 不显示失败界面
	 */
	private void showLoadFailedView(boolean flag) {
		if (flag) {
			// 显示加载失败的界面
			mLoadFailedFragment = LoadFailedFragment.getInstance(getArguments());
			manageFragment(FRAGMENT_TYPE_REPLACE, mLoadFailedFragment);
		} else {
			// 移除加载失败的界面
			if (mLoadFailedFragment != null) {
				manageFragment(FRAGMENT_TYPE_REMOVE, mLoadFailedFragment);
			}
		}
	}

	/**
	 * Fragment管理设置
	 * 
	 * @param type
	 *            动作类型: 0 -> remove ; 1 -> add ; 2 -> replace
	 * @param fragment
	 *            需要管理的Fragment
	 */
	private void manageFragment(int type, Fragment fragment) {
		// 在Fragment中管理子Fragment是使用 getChildFragmentManager()
		FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

		switch (type) {
		// remove
		case FRAGMENT_TYPE_REMOVE:
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				// FIXME 错误
				// transaction.setCustomAnimations(R.animator.fragment_slide_left_enter,
				// R.animator.fragment_slide_left_exit);
			} else {
				transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			}
			transaction.remove(fragment);
			// transaction.commit();
			break;
		// add
		case FRAGMENT_TYPE_ADD:
			transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			transaction.add(fragment, "add");
			// transaction.commit();
			break;

		// replace
		case FRAGMENT_TYPE_REPLACE:
			transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
			transaction.replace(R.id.fl_store_fragment, fragment);
			// transaction.commit();
			break;
		default:
			break;
		}
		// 使用这个方法为了保证使用这个Fragment的Activity在保存状态后出现FC
		transaction.commitAllowingStateLoss();
	}

	/** 初始化ListView */
	private void initListView() {
		mStoreList = new ArrayList<Store>();
		xListView = (XListView) mRootView.findViewById(R.id.xListView_store_fragment);
		xListView.setPullLoadEnable(true);// 允许上拉加载更多
		xListView.setPullRefreshEnable(true); // 允许下拉刷新

		mAdapter = new StoreFragmentAdapter(getActivity(), mStoreList);
		xListView.setAdapter(mAdapter);
		xListView.setXListViewListener(this);
		xListView.setOnItemClickListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		new GetStoreDataTask().execute(0);
	}

	/**
	 * 执行获取数据的任务
	 * 
	 * @param index
	 *            数据开始位置
	 */
	private void getDataTask(int index) {
		if (index >= mMaxIndex) {
			CustomToast.make(getActivity()).setText("已经到最后了(⊙o⊙)…!").show();
			return;
		} else {
			new GetStoreDataTask().execute(index);
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onRefresh() {
		// 刷新数据
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				mStoreList.clear();
				mCurDataIndex = 0;
				initData();
				onLoad();
			}
		}, 1500);

	}

	@Override
	public void onLoadMore() {
		// 加载更多
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				getDataTask(mCurDataIndex);
				onLoad();
			}
		}, 1500);
	}

	@SuppressLint("SimpleDateFormat")
	public void onLoad() {
		xListView.stopRefresh();
		xListView.stopLoadMore();
		xListView.setRefreshTime(new SimpleDateFormat("HH:mm:ss") // 更新时间设置
				.format(new Date(System.currentTimeMillis())) + "");
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// 点击中的item对应的store对象传递到另外一个Activity中
		Bundle bundle = new Bundle();
		bundle.putSerializable(INTENT_URL, (Store) parent.getAdapter().getItem(position));
		IntentUtil.startActivity(getActivity(), StoreItemActivity.class, bundle);

	}

	/**
	 * 获取数据的异步操作类
	 */
	private final class GetStoreDataTask extends AsyncTask<Integer, Integer, List<Store>> {

		// 在后台中进行的
		protected List<Store> doInBackground(Integer... params) {
			// 正在加载
			try {
				// 查询数据的起始位置 , 每页查询的数据量
				return StoreService.getStoresList(params[0], AppConfigService.getItemCount(getActivity()));
				// publishProgress(1);
			} catch (Exception e) {
				// 获取数据失败,加载失败
				return null;
			}
		}

		protected void onPreExecute() {
			LogUtil.i(TAG, "GetStoreDataTask start");
			super.onPreExecute();
		}

		protected void onPostExecute(List<Store> result) {
			// LogUtil.i(TAG, "GetStoreDataTask end " + result != null ?
			// result.toString() : "null");
			if (result != null) {
				// 后台工作完成后执行
				mStoreList.addAll(result);
				// 通知数据改变,需要重绘数据
				mAdapter.notifyDataSetChanged();
				// 自动指向下一页数据
				// mCurDataIndex = mCurDataIndex + AppConfigs.sPageItemCount;
				mCurDataIndex = mCurDataIndex + result.size();
				// 隐藏加载界面
				showLoadingView(false);
				// 显示数据列表
				xListView.setVisibility(View.VISIBLE);
			} else {
				xListView.setVisibility(View.GONE);
				CustomToast.make(getActivity()).setText("加载数据失败 \n   !-_-").show();
				showLoadFailedView(true);
			}
		}

		protected void onProgressUpdate(Integer... values) {
			// 后台工作调用 publishProgress 时执行
		}

		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		protected void onCancelled(List<Store> result) {
			super.onCancelled(result);
		}

		protected void onCancelled() {
			super.onCancelled();
		}

	}

	/**
	 * 获取店铺个数
	 */
	private final class GetStoreCountTask extends AsyncTask<Integer, Integer, Integer> {

		protected Integer doInBackground(Integer... params) {
			try {
				return StoreService.getStoresCount();
			} catch (Exception e) {
				e.printStackTrace();
				return 0;
			}
		}

		protected void onPreExecute() {
			LogUtil.d(TAG, "GetStoreCountTask start");
			super.onPreExecute();
		}

		protected void onPostExecute(Integer result) {
			LogUtil.d(TAG, "GetStoreCountTask end , result = " + result);
			if (result == 0) {
				// 如果没有数据则显示获取失败
				showLoadFailedView(true);
			} else {
				// 有数据才去初始化数据
				initData();
			}
			mMaxIndex = result;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		@Override
		protected void onCancelled(Integer result) {
			super.onCancelled(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

	}

	/** 回调方法,刷新数据 */
	public void flush() {
		// 移除加载失败界面
		showLoadFailedView(false);
		// 显示正在加载界面
		showLoadingView(true);
		// 刷新数据
		onRefresh();
	}
}
